package net.tp.struct.tree;

import java.util.*;
import java.util.function.Function;
import java.util.logging.*;

/**
 *
 * @author Trung Phan
 */
public class TreePrinter {

    private static final Logger logger = Logger.getLogger(TreePrinter.class.getName());

    public static <N> void printTree(N n, Function<N, Iterable<N>> childrenGetter) {
        String tree = toString(n, childrenGetter);
        logger.fine(tree);
    }

    public static <N extends AbstractBinNode<N>> String toString(N n) {
        return toString(n, AbstractBinNode<N>::getChildren);
    }

    public static <N> String toString(N n, Function<N, Iterable<N>> childrenGetter) {
        return toString(n, (v) -> v.toString(), childrenGetter);
    }

    public static <N> String toString(N n, Function<N, String> labelGetter, Function<N, Iterable<N>> childrenGetter) {
        if (n == null) return "⊘";

        List<StringBuilder> canvas = toCharCanvas(n, labelGetter, childrenGetter);

        StringBuilder result = null;
        for (StringBuilder builder : canvas) {
            if (result == null) {
                result = builder;
            }
            else {
                result.append('\n').append(builder);
            }
        }

        return result.toString();
    }


    private static <N> List<StringBuilder> toCharCanvas(N n, Function<N, String> labelGetter, Function<N, Iterable<N>> childrenGetter) {

        if (n == null) {
            return new ArrayList<>(Arrays.asList(new StringBuilder(" ")));
        }

        String label = labelGetter.apply(n);

        Iterable<? extends N> children = childrenGetter.apply(n);
        if (children == null) {
            return new ArrayList<>(Arrays.asList(new StringBuilder(label)));
        }
        else {
            Iterator<? extends N> iterator = children.iterator();
            boolean empty = true;
            while (iterator.hasNext()) {
                if (iterator.next() != null) {
                    empty = false;
                    break;
                }
            }

            if (empty) {
                return new ArrayList<>(Arrays.asList(new StringBuilder(label)));
            }
        }

        StringBuilder edge = new StringBuilder();
        Iterator<? extends N> iterator = children.iterator();

        List<StringBuilder> canvas = toCharCanvas(iterator.next(), labelGetter, childrenGetter);
        int width = canvas.get(0).length();
        fillSpace(edge, midPoint(canvas));
        edge.append('│');

        while (iterator.hasNext()) {
            N next = iterator.next();

            List<StringBuilder> nextCanvas = toCharCanvas(next, labelGetter, childrenGetter);
            fillSpace(edge, width + 1 + midPoint(nextCanvas));
            edge.append('│');
            width += nextCanvas.get(0).length() + 1;
            canvas = concat(canvas, nextCanvas);
        }

        canvas.add(0, edge);

        StringBuilder labelStr = new StringBuilder();

        int midPoint = midPoint(edge);
        int offset = midPoint - label.length() / 2;
        if (offset >= 0) {
            fillSpace(labelStr, offset);
            labelStr.append(label);
        }
        else {
            shift(canvas, -offset);
            width += -offset;
            labelStr.append(label);
        }

        width = Math.max(width, labelStr.length());

        fixEdge(edge);

        canvas.add(0, labelStr);

        for (StringBuilder builder : canvas) {
            fillSpace(builder, width);
        }

        return canvas;
    }

    public static void fixEdge(StringBuilder edge) {
        int min = 0, max = edge.length() - 1;
        for (; min < max && edge.charAt(min) == ' '; min++);
        for (; max > min && edge.charAt(max) == ' '; max--);

        if (min < max) {
            edge.setCharAt(min, '┌');
            edge.setCharAt(max, '┐');
            for (int i = min+1; i < max; i++) {
                edge.setCharAt(i, edge.charAt(i) == ' ' ? '─' : '┬');
            }

            int mid = (min+max)/2;
            char c = edge.charAt(mid);
            edge.setCharAt(mid, c == '─' ? '┴' : c == '┬' ? '┼' : c == '┌' ? '├' : '┤');
        }
    }

    public static List<StringBuilder> concat(List<StringBuilder> s1, List<StringBuilder> s2) {

        int w1 = s1.get(0).length();
        int w2 = s2.get(0).length();

        while (s1.size() < s2.size()) {
            StringBuilder space = new StringBuilder();
            fillSpace(space, w1);
            s1.add(space);
        }

        for (int i = 0; i < s1.size(); i++) {
            StringBuilder line = s1.get(i);
            if (i < s2.size()) {
                line.append(' ').append(s2.get(i));
            }
            else {
                fillSpace(line, w1 + w2 + 1);
            }
        }

        return s1;
    }

    public static void shift(List<StringBuilder> s, int count) {
        StringBuilder space = space(count);
        for (StringBuilder builder : s) {
            builder.insert(0, space);
        }
    }

    public static void fillSpace(StringBuilder builder, int length) {
        if (builder.length() < length) {
            builder.append(space(length - builder.length()));
        }
    }

    public static StringBuilder space(int length) {
        StringBuilder result = new StringBuilder();
        for (int i = 0; i < length; i++) {
            result.append(' ');
        }
        return result;
    }

    private static int midPoint(List<StringBuilder> canvas) {
        int midPoint = midPoint(canvas.get(0));
        if (midPoint == -1) {
            midPoint = canvas.size() > 1 ? midPoint(canvas.get(1)) : canvas.get(0).length() / 2;
        }
        return midPoint;
    }

    private static int midPoint(StringBuilder line) {
        int min = 0; int max = line.length() - 1;
        for (; min < max && line.charAt(min) == ' '; min++);
        for (; max > min && line.charAt(max) == ' '; max-- );
        return line.charAt(min) != ' ' ? (max + min) / 2 : -1;
    }
}
